#
# Copyright (c) 2014 CodiLime, Inc. All rights reserved.
#

# -*- mode: python; -*-

Import('BuildEnv')
import sys
env = BuildEnv.Clone()

env.Append(LIBPATH = env['TOP'] + '/base')
env.Append(LIBPATH = env['TOP'] + '/bfd')
env.Append(LIBPATH = env['TOP'] + '/io')

source = ['bfd_state_machine.cc', 'bfd_control_packet.cc', 'bfd_session.cc',
          'bfd_server.cc', 'bfd_common.cc', 'bfd_client.cc']
libbfd = env.Library('bfd', source)
libbfd_udp = env.Library('bfd_udp', ['bfd_udp_connection.cc'])

env.Prepend(LIBS = ['io', 'base', 'bfd', 'gunit', 'io',
                    'sandesh', 'sandeshvns', 'process_info', 'base', 'http',
                    'io', 'ssl', 'crypto', 'http_parser', 'curl', 'pugixml',
                    'boost_program_options', 'boost_thread', 'boost_chrono',
                    'boost_regex'])

contrail_bfd = env.Program(target = 'contrail-bfd', source = ['bfdd.cc'])
# env.Depends(contrail_bfd, [libbfd, File('../bfd/rest_api/libbfd_rest.a')])
env.Alias('contrail-bfd', contrail_bfd)

bfd_test_suite = env.SConscript('rest_api/SConscript', exports='BuildEnv',
                                 duplicate = 0)
bfd_test_suite += env.SConscript('test/SConscript', exports='BuildEnv',
                                 duplicate = 0)

def code_coverage(target, source, env):
    import shutil
    import os

    shutil.rmtree(target[0].path, ignore_errors = True)
    os.system('lcov --base-directory . --directory ' + Dir('.').path +
              ' --zerocounters -q')
    # execute tests
    import subprocess
    ShEnv = {env['ENV_SHLIB_PATH']: 'build/lib'}
    for test in bfd_test_suite:
        cmd = test[0].path
        logfile = open(cmd + '.log', 'w')
        print(cmd)
        subprocess.call([cmd], stdout=logfile, env=ShEnv)

    os.system('lcov --base-directory . --directory ' + Dir('.').path +
              ' -c -o bfd.info')
    os.system('genhtml -o ' + target[0].path +
              ' -t "test coverage" --num-spaces 4 bfd.info')


if env['OPT'] == 'coverage':
    test_coverage = env.Command(Dir('test_coverage'), '', code_coverage)
    env.AlwaysBuild(test_coverage)
    env.Alias('src/bfd:test_coverage', test_coverage)
